import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

class AddFingerprintTip extends StatefulWidget {
  final Map info;
  final Map params;
  const AddFingerprintTip({super.key, required this.info, required this.params});

  @override
  State<StatefulWidget> createState() => AddFingerprintTipState();
}

class AddFingerprintTipState extends State<AddFingerprintTip> {
  int _currentStep = 0;
  int _totalSteps = 0;
  bool _isAdding = false;
  bool _isConnecting = false;
  String _statusText = "准备添加指纹";
  bool _isError = false;
  bool _isSuccess = false;

  void _addFingerprint() {
    int startDate = widget.params["startDate"] != null ? DateTime.parse(widget.params["startDate"]).millisecondsSinceEpoch : 0;
    int endDate = widget.params["startDate"] != null ? DateTime.parse(widget.params["endDate"]).millisecondsSinceEpoch : 0;
    
    setState(() {
      _isConnecting = true;
      _isAdding = false;
      _isError = false;
      _isSuccess = false;
      _currentStep = 0;
      _totalSteps = 0;
      _statusText = "正在连接设备...";
    });

    TTLock.addFingerprint(
      null,
      startDate,
      endDate,
      widget.info["lockData"],
      (currentCount, totalCount) {
        setState(() {
          _isConnecting = false;
          _isAdding = true;
          _totalSteps = totalCount;
          _currentStep = currentCount;
          _statusText = "请将手指放在指纹采集器上";
        });
      },
      (fingerprintNumber) {
        setState(() {
          _isConnecting = false;
          _isAdding = false;
          _isSuccess = true;
          _statusText = "指纹添加成功！";
        });
        Map<String, dynamic> data = {
          ...widget.params,
          "startDate": startDate,
          "endDate": endDate,
          "lockId": widget.info["lockId"],
          "fingerprintType": 1,
          "fingerprintNumber": fingerprintNumber,
        };
        _uploadFingerprint(data);
      },
      (errorCode, errorMsg) {
        setState(() {
          _isConnecting = false;
          _isAdding = false;
          _isError = true;
          _statusText = "连接设备失败，请重试";
        });
        EasyLoading.showError("$errorCode, $errorMsg");
      });
  }

  void _uploadFingerprint(Map<String, dynamic> data) async {
    await lockApi.uploadFingerprint(data);
    EasyLoading.showToast("指纹添加成功");
    Future.delayed(const Duration(seconds: 1), () {
      Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_LOCK_FINGERPRINT, ModalRoute.withName(Keys.DEVICE_LOCK_DETAIL), arguments: widget.info);
    });
  }

  Widget _buildProgressIndicator() {
    double progress = _totalSteps > 0 ? _currentStep / _totalSteps : 0;
    Color indicatorColor = _isError 
        ? ThemeVars.colorError 
        : _isSuccess 
            ? ThemeVars.colorSuccess 
            : ThemeVars.colorPrimary;
    
    return Container(
      padding: const EdgeInsets.all(4),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 140,
            height: 140,
            padding: const EdgeInsets.all(8),
            child: _isConnecting || (!_isAdding && !_isError && !_isSuccess)
                ? CircularProgressIndicator(
                    value: _isConnecting ? null : 0,
                    strokeWidth: 4,
                    backgroundColor: _isConnecting ? null : ThemeVars.colorPrimaryLight,
                    valueColor: AlwaysStoppedAnimation<Color>(indicatorColor),
                  )
                : TweenAnimationBuilder(
                    tween: Tween<double>(begin: 0, end: progress),
                    duration: const Duration(milliseconds: 300),
                    builder: (context, double value, child) {
                      return CircularProgressIndicator(
                        value: _isAdding ? value : 1.0,
                        strokeWidth: 4,
                        backgroundColor: ThemeVars.colorPrimaryLight,
                        valueColor: AlwaysStoppedAnimation<Color>(indicatorColor),
                      );
                    },
                  ),
          ),
          Icon(
            _isError 
                ? Icons.error_outline 
                : _isSuccess 
                    ? Icons.check_circle_outline
                    : Icons.fingerprint,
            size: 60,
            color: indicatorColor,
          ),
          if (_isAdding && _totalSteps > 0)
            Positioned(
              bottom: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: const [
                    BoxShadow(
                      color: Color.fromRGBO(0, 0, 0, 0.1),
                      blurRadius: 4,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "第",
                      style: const TextStyle(
                        fontSize: 12,
                        color: ThemeVars.colorTextSec,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 4),
                      child: Text(
                        "$_currentStep",
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: ThemeVars.colorPrimary,
                        ),
                      ),
                    ),
                    Text(
                      "/$_totalSteps次",
                      style: const TextStyle(
                        fontSize: 12,
                        color: ThemeVars.colorTextSec,
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildStatusText() {
    return Container(
      margin: const EdgeInsets.only(left: 32, right: 32, top: 40, bottom: 24),
      child: Column(
        children: [
          Text(
            _statusText,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
              color: ThemeVars.colorText,
            ),
            textAlign: TextAlign.center,
          ),
          if (!_isConnecting && !_isAdding && !_isError && !_isSuccess) ...[
            const SizedBox(height: 12),
            const Text(
              "添加过程中，请根据提示，在指纹采集器上进行多次的抬起、按压",
              style: TextStyle(
                fontSize: 14,
                height: 1.5,
                color: ThemeVars.colorTextSec,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildActionButton() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      child: Button(
        type: ButtonType.primary,
        onPressed: (_isConnecting || _isAdding) ? null : _addFingerprint,
        child: Text(
          _isError 
              ? "重试" 
              : _isConnecting 
                  ? "连接中..." 
                  : _isAdding 
                      ? "添加中..." 
                      : "开始添加",
          style: const TextStyle(fontSize: 16),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "添加指纹",
      child: Column(
        children: [
          Expanded(
            child: Center(
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _buildProgressIndicator(),
                    _buildStatusText(),
                  ],
                ),
              ),
            ),
          ),
          _buildActionButton(),
        ],
      ),
    );
  }
}